<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <meta name="decorator" content="default"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>七牛云文件管理</title>

  <!-- CSS -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.4.1/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" th:href="@{/statics/css/qiniu.css}">
</head>
<body>

<!-- 页面内容 -->
<div class="search-area">
  <form class="form-inline">
    <div class="form-group">
      <label>存储空间：</label>
      <select id="bucketSelect" class="form-control">
        <option value="lemonworkspace">默认空间</option>
      </select>
    </div>
    <div class="form-group" style="margin-left: 20px;">
      <label>文件名称：</label>
      <input type="text" id="prefixInput" class="form-control" placeholder="输入文件名前缀">
    </div>
    <button type="button" class="btn btn-primary" onclick="searchFiles()">
      <i class="fa fa-search"></i> 搜索
    </button>
    <button type="button" class="btn btn-default" onclick="resetSearch()">
      <i class="fa fa-refresh"></i> 重置
    </button>
  </form>
</div>

<div class="operation-area">
  <div class="btn-group">
    <button type="button" class="btn btn-success" onclick="showUploadModal()">
      <i class="fa fa-upload"></i> 上传文件
    </button>
    <button type="button" class="btn btn-default" onclick="refreshList()">
      <i class="fa fa-refresh"></i> 刷新
    </button>
  </div>
</div>

<div class="file-list-area">
  <table class="table table-striped table-bordered table-hover">
    <thead>
    <tr>
      <th width="30%">文件名</th>
      <th width="10%">文件大小</th>
      <th width="15%">文件类型</th>
      <th width="20%">上传时间</th>
      <th width="25%">操作</th>
    </tr>
    </thead>
    <tbody id="fileTableBody">
    <tr>
      <td colspan="5" style="text-align: center;">加载中...</td>
    </tr>
    </tbody>
  </table>
</div>

<!-- 上传模态框 -->
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">上传文件</h4>
      </div>
      <div class="modal-body">
        <form id="uploadForm" enctype="multipart/form-data">
          <div class="form-group">
            <label>选择文件：</label>
            <input type="file" id="fileInput" name="file" class="form-control" required>
          </div>
          <div class="form-group">
            <label>存储空间：</label>
            <select id="uploadBucket" name="bucket" class="form-control">
              <option value="lemonworkspace">默认空间</option>
            </select>
          </div>
          <div class="progress" style="display: none;" id="uploadProgress">
            <div class="progress-bar" role="progressbar" style="width: 0%;">0%</div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" onclick="doUpload()">上传</button>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.4.1/dist/js/bootstrap.min.js"></script>

<script>
  // 修复：使用正确的baseUrl
  var baseUrl = '../../pms/qiniu';  // 修改这一行

  function showUploadModal() {
    console.log('显示上传模态框');
    $('#uploadForm')[0].reset();
    $('#uploadProgress').hide();
    $('#uploadModal').modal('show');
  }

  function searchFiles() {
    console.log('搜索文件');
    loadFileList();
  }

  function resetSearch() {
    console.log('重置搜索');
    $('#prefixInput').val('');
    $('#bucketSelect').val('lemonworkspace');
    loadFileList();
  }

  function refreshList() {
    console.log('刷新列表');
    loadFileList();
  }

  function loadFileList() {
    console.log('开始加载文件列表');

    $('#fileTableBody').html('<tr><td colspan="5" style="text-align: center;">加载中...</td></tr>');

    var params = {
      prefix: $('#prefixInput').val(),
      bucket: $('#bucketSelect').val(),
      marker: ''
    };

    $.ajax({
      url: baseUrl + '/list',  // 这里会使用修复后的baseUrl
      type: 'GET',
      data: params,
      success: function(response) {
        console.log('文件列表响应:', response);
        if (response.code === 0) {
          renderFileList(response.data);
        } else {
          alert('加载失败：' + response.msg);
          $('#fileTableBody').html('<tr><td colspan="5" style="text-align: center;">加载失败</td></tr>');
        }
      },
      error: function(xhr, status, error) {
        console.error('加载错误:', error);
        alert('网络错误，请稍后重试');
        $('#fileTableBody').html('<tr><td colspan="5" style="text-align: center;">网络错误</td></tr>');
      }
    });
  }

  // 其他函数保持不变...
  function renderFileList(data) {
    console.log('渲染文件列表:', data);
    var tbody = $('#fileTableBody');
    tbody.empty();

    if (!data || !data.items || data.items.length === 0) {
      tbody.html('<tr><td colspan="5" style="text-align: center;">暂无文件</td></tr>');
      return;
    }

    data.items.forEach(function(file) {
      var row = '<tr>' +
              '<td>' +
              '<div class="file-name">' +
              '<i class="fa fa-file-o file-icon"></i>' +
              '<span title="' + file.key + '">' + file.key + '</span>' +
              '</div>' +
              '</td>' +
              '<td>' + formatFileSize(file.size) + '</td>' +
              '<td>' + (file.mimeType || '未知') + '</td>' +
              '<td>' + formatTime(file.putTime) + '</td>' +
              '<td>' +
              '<button type="button" class="btn btn-xs btn-success" onclick="downloadFile(\'' + file.url + '\', \'' + file.key + '\')">下载</button> ' +
              '<button type="button" class="btn btn-xs btn-danger" onclick="deleteFile(\'' + file.key + '\')">删除</button>' +
              '</td>' +
              '</tr>';
      tbody.append(row);
    });
  }

  function doUpload() {
    console.log('开始上传文件');

    var fileInput = $('#fileInput')[0];
    if (!fileInput.files || fileInput.files.length === 0) {
      alert('请选择要上传的文件');
      return;
    }

    var formData = new FormData();
    formData.append('file', fileInput.files[0]);
    formData.append('bucket', $('#uploadBucket').val());

    $('#uploadProgress').show();

    $.ajax({
      url: baseUrl + '/upload',  // 使用修复后的baseUrl
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      xhr: function() {
        var xhr = new window.XMLHttpRequest();
        xhr.upload.addEventListener("progress", function(evt) {
          if (evt.lengthComputable) {
            var percentComplete = (evt.loaded / evt.total) * 100;
            $('.progress-bar').css('width', percentComplete + '%').text(percentComplete.toFixed(1) + '%');
          }
        }, false);
        return xhr;
      },
      success: function(response) {
        console.log('上传响应:', response);
        if (response.code === 0) {
          alert('上传成功');
          $('#uploadModal').modal('hide');
          loadFileList();
        } else {
          alert('上传失败：' + response.msg);
        }
      },
      error: function(xhr, status, error) {
        console.error('上传错误:', error);
        alert('上传失败，请检查网络连接');
      },
      complete: function() {
        $('#uploadProgress').hide();
      }
    });
  }

  function deleteFile(fileName) {
    if (!confirm('确定要删除文件 "' + fileName + '" 吗？')) {
      return;
    }

    var params = {
      fileName: fileName,
      bucket: $('#bucketSelect').val()
    };

    $.ajax({
      url: baseUrl + '/delete',  // 使用修复后的baseUrl
      type: 'POST',
      contentType: 'application/json',
      data: JSON.stringify(params),
      success: function(response) {
        console.log('删除响应:', response);
        if (response.code === 0) {
          alert('删除成功');
          loadFileList();
        } else {
          alert('删除失败：' + response.msg);
        }
      },
      error: function(xhr, status, error) {
        console.error('删除错误:', error);
        alert('删除失败，请稍后重试');
      }
    });
  }

  function downloadFile(url, fileName) {
    window.open(url);
  }

  function formatFileSize(bytes) {
    if (!bytes) return '0 B';
    const units = ['B', 'KB', 'MB', 'GB'];
    let size = bytes;
    let unitIndex = 0;
    while (size >= 1024 && unitIndex < units.length - 1) {
      size /= 1024;
      unitIndex++;
    }
    return size.toFixed(1) + ' ' + units[unitIndex];
  }

  function formatTime(timestamp) {
    if (!timestamp) return '-';
    var date = new Date(timestamp / 10000);
    return date.toLocaleString();
  }

  $(document).ready(function() {
    console.log('页面加载完成，开始加载文件列表');
    loadFileList();
  });
</script>

</body>
</html>